import axios from 'axios';
import config from '../config/index.js';
import { BusinessError } from '../middleware/errorHandler.js';

// 构建系统提示词
const buildSystemPrompt = (expert, domain, preconditions = {}) => {
  let prompt = `你是一位专业的${domain.name}专家，名字叫${expert.nickname}。`;
  
  if (expert.bio) {
    prompt += `\n\n关于你的介绍：${expert.bio}`;
  }
  
  if (domain.welcome_message_1) {
    prompt += `\n\n领域介绍：${domain.welcome_message_1}`;
  }
  
  // 添加前置条件信息
  if (preconditions && Object.keys(preconditions).length > 0) {
    prompt += '\n\n用户提供的背景信息：';
    Object.entries(preconditions).forEach(([key, value]) => {
      prompt += `\n- ${key}: ${value}`;
    });
  }
  
  prompt += `\n\n请以专业、友善的态度回答用户的问题。回答要准确、实用，并且符合${domain.name}领域的专业标准。`;
  
  return prompt;
};

// 构建用户消息
const buildUserMessage = (question, preconditions = {}) => {
  let message = question;
  
  // 如果有前置条件，可以在这里添加到用户消息中
  if (preconditions && Object.keys(preconditions).length > 0) {
    message = `背景信息：${JSON.stringify(preconditions, null, 2)}\n\n问题：${question}`;
  }
  
  return message;
};

// OpenAI API调用
const callOpenAI = async (messages) => {
  try {
    const response = await axios.post(
      `${config.ai.baseURL}/chat/completions`,
      {
        model: config.ai.model,
        messages,
        max_tokens: 2000,
        temperature: 0.7,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
      },
      {
        headers: {
          'Authorization': `Bearer ${config.ai.apiKey}`,
          'Content-Type': 'application/json'
        },
        timeout: 30000 // 30秒超时
      }
    );
    
    const choice = response.data.choices[0];
    if (!choice || !choice.message) {
      throw new BusinessError('AI服务返回数据格式错误');
    }
    
    return {
      answer: choice.message.content.trim(),
      requestId: response.data.id,
      usage: response.data.usage,
      model: response.data.model
    };
  } catch (error) {
    if (error.response) {
      const status = error.response.status;
      const message = error.response.data?.error?.message || 'AI服务调用失败';
      
      if (status === 401) {
        throw new BusinessError('AI服务认证失败');
      } else if (status === 429) {
        throw new BusinessError('AI服务调用频率超限');
      } else if (status >= 500) {
        throw new BusinessError('AI服务暂时不可用');
      } else {
        throw new BusinessError(`AI服务错误: ${message}`);
      }
    } else if (error.code === 'ECONNABORTED') {
      throw new BusinessError('AI服务响应超时');
    } else {
      throw new BusinessError('AI服务连接失败');
    }
  }
};

// 通义千问API调用（示例）
const callQianwen = async (messages) => {
  // 这里是通义千问的实现示例
  // 实际使用时需要根据通义千问的API文档进行实现
  throw new BusinessError('通义千问服务暂未实现');
};

// 主要的AI问答函数
export const askAI = async (question, expert, domain, preconditions = {}) => {
  if (!question || !question.trim()) {
    throw new BusinessError('问题不能为空');
  }
  
  if (!expert || !domain) {
    throw new BusinessError('专家或领域信息缺失');
  }
  
  // 构建消息
  const systemPrompt = buildSystemPrompt(expert, domain, preconditions);
  const userMessage = buildUserMessage(question, preconditions);
  
  const messages = [
    {
      role: 'system',
      content: systemPrompt
    },
    {
      role: 'user',
      content: userMessage
    }
  ];
  
  try {
    let result;
    
    // 根据配置选择AI服务商
    switch (config.ai.provider) {
      case 'openai':
        result = await callOpenAI(messages);
        break;
      case 'qianwen':
        result = await callQianwen(messages);
        break;
      default:
        throw new BusinessError('不支持的AI服务商');
    }
    
    return result;
  } catch (error) {
    console.error('AI服务调用失败:', error);
    throw error;
  }
};

// 开发环境模拟AI回答
export const mockAIAnswer = async (question, expert, domain, preconditions = {}) => {
  // 模拟API调用延迟
  await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000));
  
  const mockAnswers = [
    `作为${expert.nickname}，我认为您的问题很有意思。基于您提供的信息，我建议您可以从以下几个方面来考虑...`,
    `根据我在${domain.name}领域的经验，针对您的情况，我有以下几点建议...`,
    `这是一个很常见的问题。在${domain.name}领域中，我们通常会这样处理...`,
    `感谢您的提问。基于您的背景信息，我认为最重要的是...`
  ];
  
  const randomAnswer = mockAnswers[Math.floor(Math.random() * mockAnswers.length)];
  
  return {
    answer: randomAnswer + '\n\n（这是开发环境的模拟回答）',
    requestId: 'mock_' + Date.now(),
    usage: {
      prompt_tokens: 100,
      completion_tokens: 50,
      total_tokens: 150
    },
    model: 'mock-model'
  };
};

// 主要的问答函数（根据环境选择真实或模拟）
export const getAIAnswer = async (question, expert, domain, preconditions = {}) => {
  // 开发环境使用模拟回答
  if (process.env.NODE_ENV === 'development' && !config.ai.apiKey) {
    return await mockAIAnswer(question, expert, domain, preconditions);
  }
  
  return await askAI(question, expert, domain, preconditions);
};

// 验证AI配置
export const validateAIConfig = () => {
  if (!config.ai.provider) {
    throw new BusinessError('AI服务商未配置');
  }
  
  if (!config.ai.apiKey && process.env.NODE_ENV !== 'development') {
    throw new BusinessError('AI服务API密钥未配置');
  }
  
  if (!config.ai.baseURL && config.ai.provider === 'openai') {
    throw new BusinessError('AI服务基础URL未配置');
  }
  
  return true;
};

export default {
  askAI,
  getAIAnswer,
  mockAIAnswer,
  validateAIConfig
};
